package com.dotflat.xj.controller;

import com.dotflat.cc.po.ChildrenImportPO;
import com.dotflat.rest.controller.RestfulBaseController;
import com.dotflat.util.AssertUtil;
import com.dotflat.util.TargetUtil;
import com.dotflat.util.excelUtil.ExcelUtil;
import com.dotflat.util.excelUtil.StringUtils;
import com.dotflat.xj.domain.Target;
import com.dotflat.xj.domain.TargetProjectValue;
import com.dotflat.xj.po.ImportTargetPO;
import com.dotflat.xj.po.TargetPO;
import com.dotflat.xj.repository.TargetProjectValueRepository;
import com.dotflat.xj.service.TargetService;
import com.matt.commons.dto.sso.AreaDTO;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.page.PagerQuery;
import com.matt.domain.Children;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.utils.CopyUtils;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.matt.foundation.constant.RequestConstant.TICKET;

/**
 * 巡检对象Controller
 *
 * @author #
 * @date 2021-11-25
 */
@RestController
@RequestMapping("/api/xj_target")
@Slf4j
@Api(tags = "巡检 - 目标对象")
public class XJTargetController extends RestfulBaseController<Target, TargetService, TargetPO> {

    @Autowired
    private TargetService targetService;

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private TargetProjectValueRepository targetProjectValueRepository;

    @Autowired
    public void setBaseService(TargetService service) {
        super.setBaseService(service);
    }


    @Override
    public StatusResponse add(@RequestHeader(TICKET)String ticket, TargetPO param) {
        StaffDTO staffDTO = ssoCallService.getStaffDTO(ticket);
        String groupId = ssoCallService.getAreaGroupAdmin(ticket);
        Target target;
        if (Objects.isNull(param.getIsGroup())){
            param.setIsGroup(2);
        }
        if (Objects.nonNull(param.getId()) && !StringUtils.equals("",param.getId())){
            target =  targetService.getId(param.getId());
        }else {
            target =  new Target();
        }
        if (Objects.nonNull(target)){
            if (StringUtils.equals(target.getAreaId(),"0") && StringUtils.equals(target.getGroupId(),"0")){
                throw new BusinessException(ErrorCode.IS_TARGET, "系统公共对象禁止修改！");
            }
        }
        if (param.getIsGroup() == 1){
            if (Objects.nonNull(groupId) && !StringUtils.equals(groupId,"")){
                CopyUtils.copyProperties(param,target);
                target.setAreaId("0");
                target.setGroupId(groupId);
                target.setCreatedBy(staffDTO.getId());
                return StatusResponse.success(targetService.save(target));
            }else {
                throw new BusinessException(ErrorCode.IS_TARGET, "非集团管理员！");
            }
        }else if (param.getIsGroup() == 0){
            if (Objects.nonNull(groupId) && !StringUtils.equals(groupId,"")){
                CopyUtils.copyProperties(param,target);
                target.setAreaId(staffDTO.getAreaId());
                target.setGroupId(groupId);
                target.setCreatedBy(staffDTO.getId());
                return StatusResponse.success(targetService.save(target));
            }else {
                throw new BusinessException(ErrorCode.IS_TARGET, "非集团管理员！");
            }
        }else {
            param.setGroupId(groupId);
            return super.add(ticket, param);
        }
    }

    @ApiOperation(value = "巡检分类 - list")
    @PostMapping("/getList")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "typeName", value = "分类名称", required = false, dataType = "string")
    })
    public StatusResponse getList(@RequestHeader(TICKET) String ticket, String typeName,String status, PagerQuery pagerQuery) {
        return StatusResponse.success(targetService.getList(ticket, typeName,status,pagerQuery));
    }


    @ApiOperation(value = "项目 - list")
    @PostMapping("/project_list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类ID", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "sortName", value = "分项名称", required = false, dataType = "string")
    })
    public StatusResponse projectList(@RequestHeader(TICKET) String ticket, String targetId,String sortName) {
        List<Map>  mapList = targetService.projectList(ticket, targetId, sortName);
        return StatusResponse.success(mapList);
    }

    @ApiOperation(value = "项目 - 保存")
    @PostMapping("/add_project")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类ID", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "sortName", value = "分项名称", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "parentId", value = "父级ID，父级0", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "sortValue", value = "最高值", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "sortValueLow", value = "最低值", required = false, dataType = "string")

    })
    public StatusResponse addProject(@RequestHeader(TICKET) String ticket, String targetId,String sortName,String parentId,String sortValue,String sortValueLow ) {
        StaffDTO staff = cache.getStaff(ticket);
        AreaDTO areaDTO = cache.getArea(ticket);
        Target target = targetService.getId(targetId);
        if (AssertUtil.isEmpty(target)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "对象不存在！");
        }
        TargetProjectValue targetProjectValue1 = targetProjectValueRepository.getOne(parentId);
        if (AssertUtil.isEmpty(targetProjectValue1)) {
            throw new BusinessException(ErrorCode.IS_TARGET, "父级不存在！");
        }
        //父级不计分
        if (!StringUtils.equals(parentId, "0")) {

            List<TargetProjectValue> list = targetProjectValueRepository.getTargetIdProject(target.getId());
            //统计的数据
            target.setProjectCount((TargetUtil.getFraction(target.getConclusionType()) * list.size()) + TargetUtil.getFraction(target.getConclusionType()));
            target.setProjectNumber(target.getProjectNumber() + 1);
            target.setBelonging(areaDTO.getName());
            targetService.save(target);
        }
        return StatusResponse.success(targetService.addProject(staff,areaDTO, target, sortName,parentId,sortValue,sortValueLow));
    }

    @ApiOperation(value = "详情")
    @PostMapping("/details")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类ID", required = true, dataType = "string")
    })
    public StatusResponse details(@RequestHeader(TICKET) String ticket, String targetId) {
        return StatusResponse.success(targetService.details(ticket, targetId));
    }


    @ApiOperation(value = "项目 - 添加，页")
    @PostMapping("/get_parent")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类ID", required = true, dataType = "string")
    })
    public StatusResponse getParent(@RequestHeader(TICKET) String ticket, String targetId) {
        return StatusResponse.success(targetService.getParent(ticket, targetId));
    }

    @ApiOperation(value = "项目 - 编辑")
    @PostMapping("/get_project")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类ID", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目ID", required = true, dataType = "string")
    })
    public StatusResponse getParent(@RequestHeader(TICKET) String ticket, String targetId, String projectId) {
        return StatusResponse.success(targetService.getProject(ticket, targetId,projectId));
    }



    @ApiOperation(value = "项目 - 保存")
    @PostMapping("/update_project")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "sortName", value = "分项名称", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "parentId", value = "父级ID，父级0", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "sortValue", value = "最高值", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "sortValueLow", value = "最低值", required = false, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目ID", required = true, dataType = "string")

    })
    public StatusResponse updateProject(@RequestHeader(TICKET) String ticket, String projectId,String sortName,String parentId,String sortValue,String sortValueLow ) {
        return StatusResponse.success(targetService.updateProject(ticket, projectId, sortName,parentId,sortValue,sortValueLow));
    }

    @ApiOperation(value = "app - 日常巡检项 -list")
    @PostMapping("/app_list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string")
    })
    public StatusResponse appList(@RequestHeader(TICKET) String ticket) {
        List<Map> list =  targetService.appList(ticket);
        return StatusResponse.success(list);
    }

    @ApiOperation(value = "app - 巡检信息")
    @PostMapping("/app_project")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类ID", required = true, dataType = "string")
    })
    public StatusResponse appList(@RequestHeader(TICKET) String ticket, String targetId) {
        Map map =  targetService.getRecord(ticket,targetId);
        return StatusResponse.success(map);
    }


    @ApiOperation(value = "app - 班级巡检 -list")
    @PostMapping("/app_class_list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "classId", value = "班级id" , required = true, dataType = "string")
    })
    public StatusResponse appClassList(@RequestHeader(TICKET) String ticket,String classId) {
        List<Target> list =  targetService.appClassList(ticket,classId);
        return StatusResponse.success(list);
    }


    @ApiOperation(value = "停用-类别")
    @PostMapping("/stop")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类Id" , required = true, dataType = "string")
    })
    public StatusResponse stop(@RequestHeader(TICKET) String ticket,String targetId) {
        Target target =targetService.stop(ticket,targetId,"1");
        return StatusResponse.success(target);
    }

    @ApiOperation(value = "启用-类别")
    @PostMapping("/using")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "targetId", value = "分类Id" , required = true, dataType = "string")
    })
    public StatusResponse using(@RequestHeader(TICKET) String ticket,String targetId) {
        Target target = targetService.stop(ticket,targetId,"0");
        return StatusResponse.success(target);
    }

    @ApiOperation(value = "停用项目下所有")
    @PostMapping("/stop_project")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "projectId", value = "项目ID" , required = true, dataType = "string")
    })
    public StatusResponse stopProject(@RequestHeader(TICKET) String ticket,String projectId) {
        targetService.stopProject(ticket,projectId);
        return StatusResponse.success("停用成功");
    }



    @ApiOperation(value = "导入巡检数据")
    @PostMapping("/importTarget")
    @ApiResponses({
            @ApiResponse(code = 200,message = "OK", response = Children.class),
    })
    @Transactional(rollbackOn = RuntimeException.class)
    public StatusResponse importTarget(@RequestHeader(TICKET) String ticket,
                                      @RequestParam MultipartFile file) throws Exception{
        StaffDTO staffDTO = ssoCallService.getStaffDTO(ticket);
        String groupId = ssoCallService.getAreaGroupAdmin(ticket);
        AreaDTO areaDTO = cache.getArea(ticket);
        ExcelUtil<ImportTargetPO> util = new ExcelUtil<ImportTargetPO>(ImportTargetPO.class);
        List<ImportTargetPO> importExcel = util.importExcel(file.getInputStream());
        String message = targetService.importTarget(staffDTO,areaDTO,groupId,importExcel);
        return StatusResponse.success(message);
    }

}